import React, { Component } from 'react'
import { Spin, message } from 'antd'
import { get, post } from '@/utils/requestUtil'
import './index.css'
import FormWidget from '@/components/basicWidget/FormWidget'

class SqlCard extends Component {

    constructor(props) {
        super(props)
        this.state = {
            loading: true,
            commandCode: null,
            sqlCodeInfo: {},
            disabled: false
        }
    }

    async componentDidMount() {
        let commandCode = this.props.commandCode
        let sqlCodeInfo = {}
        let disabled = false
        if (commandCode != null) {
            const response = await get(`/api/sqlCode/code/${commandCode}`)
            if (response && response.data) {
                sqlCodeInfo = response.data
                disabled = true
                await new Promise(resolve => {
                    this.setState({
                        commandCode,
                        sqlCodeInfo,
                        disabled
                    }, resolve)
                })
            }
        }
        await new Promise(resolve => { this.setState({ loading: false }, resolve) })
    }

    render() {
        if (this.state.loading === true) return <Spin />
        return (
            <div className='SqlCard-main'>
                <FormWidget
                    code='sqlCode'
                    initFormData={this.state.sqlCodeInfo}
                    ref={ref => { if (ref) { this.formEdit = ref } }}
                    refData={{
                        disabled: this.state.disabled
                    }}
                    saveSqlCode={async () => {
                        if (!await this.formEdit.validateFormData()) {
                            return false
                        }
                        const response = await post('/api/sqlCode/save', { body: JSON.stringify(this.formEdit.state.formData) })
                        if (response && response.data === false) {
                            message.warning(response.message)
                            return
                        }
                        await new Promise(resolve => {
                            this.setState({
                                sqlCodeInfo: response.data,
                                disabled: true
                            }, resolve)
                        })
                        message.success('保存成功')
                    }}
                >
                </FormWidget>
            </div>
        )
    }
}

export default SqlCard